package com.qianchang.microfinance.view.mine.bill;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.allinpay.appayassistex.APPayAssistEx;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.OneLineLinearLayout;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.MyBillBean;
import com.qianchang.microfinance.bean.RepayDetailBean;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.hsrecharge.HSReChargeActivity;
import com.qianchang.microfinance.view.yfbpay.YBPayActivity;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 还款   if (bean.getOverdueDays() < 0) {//==0立即还款/大于0 逾期还款
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/17 14:50
 */
public class PayBackActivity extends BaseActivity{

    private static final String TAG = "PayBackActivity";
    public static final String ENTITY_KEY = "MyBillBean_Bean";

    @BindView(R.id.oll_repay_total_amount)
    OneLineLinearLayout ollRepayTotalAmount;

    @BindView(R.id.oll_repay_principal)
    OneLineLinearLayout ollRepayPrincipal;

    @BindView(R.id.oll_interest)
    OneLineLinearLayout ollInterest;

    @BindView(R.id.oll_overdue_fine)
    OneLineLinearLayout ollOverdueFine;

    @BindView(R.id.btn_payback)
    Button btnPayback;

    @BindView(R.id.btn_charge)
    Button btnCharge;

    private MyBillBean.Bean bean;
    private RepayDetailBean repayDetailBean;
    private String payData;
    private String serverMode = "00";
    private static int REQUESTCODE = 100;
    private static int RESULTCODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payback);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.title_repayment));

        btnPayback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog alertDialog = new AlertDialog.Builder(PayBackActivity.this)
                        .setTitle("提示")
                        .setMessage("是否执行还款？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //执行提前还款
                                dialog.dismiss();
                                if (bean.getOverdueDays() == 0) {
                                    // 正常还款 （余额支付） micoolWong
                                    paybackByQianpen();
                                } else {
                                    // 逾期还款（通联支付） micoolWong
                                    //paybackByTonglian();
//                                    paybackTonglianH5();

                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ENTITY_KEY, bean);// MyBillBean.Bean
//                                    startActivity(TLPayActivity.class, bundle);                   //立即还款/逾期还款         注释掉通联支付 2018.8.16

                                    startActivity(YBPayActivity.class, bundle);            //修改成易宝支付
                                    PayBackActivity.this.finish();
//                                    startActivityForResult(YBPayActivity.class,bundle,REQUESTCODE);     //修改成易宝支付

                                }
                            }
                        }).setCancelable(false).create();
                alertDialog.show();
            }
        });
        //去充值
        btnCharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去充值
                Bundle bundle = new Bundle();
                bundle.putString("money",bean.getPaymentAmount()+"");
                bundle.putString("rechargeType","3");
                startActivity(HSReChargeActivity.class,bundle,true);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        bean = (MyBillBean.Bean) bundle.getSerializable(MyBillAdapter.ENTITY_KEY);
        Log.i("wmy", "initData bean = " + bean.toString());
        if (bean != null) {
            getDetail();

            //还款总额
            ollRepayTotalAmount.setRightContent(bean.getPaymentAmount());//还款总额

            if (bean.getOverdueDays() == 0) {//==0立即还款
                ollOverdueFine.setVisibility(View.GONE);
                btnCharge.setVisibility(View.GONE);
            } else{//大于0 逾期还款
                ollOverdueFine.setVisibility(View.VISIBLE);
                btnCharge.setVisibility(View.GONE);
            }
        } else {
            bean = new MyBillBean.Bean();
            ToastUtil.getInstant().show(PayBackActivity.this, getString(R.string.data_error));
        }
    }

    /**
     * 获取还款金额详情
     */
    private void getDetail() {
        show();
        HttpParams params = new HttpParams();
        params.put("projectId", bean.getProjectId()); //产品Id项目id
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.REPAY_DETAIL, params, new RequestCallBack<RepayDetailBean>() {
            @Override
            public void onSuccess(JsonResult<RepayDetailBean> response) {
                dismiss();
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    refreshView(response.getObject());
                } else {
                    ToastUtil.getInstant().show(PayBackActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(PayBackActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(PayBackActivity.this, msg);
            }
        });
    }

    private void refreshView(RepayDetailBean repayDetailBean) {
        if(repayDetailBean != null){
            this.repayDetailBean = repayDetailBean;
            ollInterest.setRightContent(FormatUtil.numKbPointFormat(repayDetailBean.getInterest()));//利息
            ollOverdueFine.setRightContent(FormatUtil.numKbPointFormat(repayDetailBean.getOverdue()));//逾期罚息
            ollRepayPrincipal.setRightContent(FormatUtil.numKbPointFormat(repayDetailBean.getPrincipal()));//本金
        }else {
            ToastUtil.getInstant().show(getApplicationContext(),getString(R.string.data_error));
        }

    }

    /**
     * 立即还款(钱盆)
     */
    private void paybackByQianpen(){
        show();
        HttpParams params = new HttpParams();
        try{
            params.put("projectId", bean.getProjectId()); //项目id
            params.put("period", bean.getPeriod()); //产品的哪一期
            params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
            /**
             * 订单类型：1：开通会员 2：充值金币  3：充值余额  4：手工提现 5：自动提现 6.余额正常还款 7.银行卡正常还款
             * 8.余额逾期还款 9.银行卡逾期还款 10.代还
             */
            params.put("rechargeType", "6"); // 类型 micoolWong
            params.put("principal", FormatUtil.numKbPointFormat(repayDetailBean.getPrincipal())); //本金
            params.put("interest", FormatUtil.numKbPointFormat(repayDetailBean.getInterest())); //利息
            params.put("overdue", FormatUtil.numKbPointFormat(repayDetailBean.getOverdue())); //逾期费用

            DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.REPAY, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(JsonResult<String> response) {
                    dismiss();
                    if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                        ToastUtil.getInstant().show(PayBackActivity.this, response.getDescription());
                        startActivity(MyBillActivity.class, true);
                    } else {
                        if(response.getDescription().equals("账户余额不足")){
                            final AlertDialog alertDialog = new AlertDialog.Builder(PayBackActivity.this)
                                    .setTitle("提示")
                                    .setMessage("账户余额不足,是否立即执行充值操作？")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            //执行提前还款
                                            dialog.dismiss();
                                            //去充值
                                            Bundle bundle = new Bundle();
                                            bundle.putString("money",bean.getPaymentAmount()+"");
                                            bundle.putString("rechargeType","3");
                                            startActivity(HSReChargeActivity.class,bundle,true);
                                        }
                                    }).setCancelable(false).create();
                            alertDialog.show();
                        }else{
                            ToastUtil.getInstant().show(PayBackActivity.this, response.getDescription());
                        }
                    }
                }

                @Override
                public void onFailure(String msg) {
                    dismiss();
                    ToastUtil.getInstant().show(PayBackActivity.this, msg);// getString(R.string.msg_indentity_code_send_fail));
                }

                @Override
                public void onConnectFailure(String msg) {
                    ToastUtil.getInstant().show(PayBackActivity.this, msg);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 通联支付(H5)
     */
    private void paybackTonglianH5(){
        Bundle bundle = new Bundle();
        bundle.putSerializable("projectId", bean.getProjectId()); //项目id
        bundle.putSerializable("period", bean.getPeriod()); //产品Id
        bundle.putSerializable("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        /**
         * 订单类型：1：开通会员 2：充值金币  3：充值余额  4：手工提现 5：自动提现 6.余额正常还款 7.银行卡正常还款
         * 8.余额逾期还款 9.银行卡逾期还款 10.代还
         */
        bundle.putSerializable("rechargeType", "9"); // 类型 micoolWong
        bundle.putSerializable("principal", FormatUtil.numKbPointFormat(repayDetailBean.getPrincipal())); //本金
        bundle.putSerializable("interest", FormatUtil.numKbPointFormat(repayDetailBean.getInterest())); //利息
        bundle.putSerializable("overdue", FormatUtil.numKbPointFormat(repayDetailBean.getOverdue())); //逾期费用
        startActivity(PayTonglianActivity.class, bundle);
    }

    /**
     * 立即还款(通联)
     */
    private void paybackByTonglian() {
        show();
        HttpParams params = new HttpParams();
        try{
        //迪蒙的 注释掉
        params.put("projectId", bean.getProjectId()); //项目id
        params.put("period", bean.getPeriod()); //产品Id
        params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        /**
         * 订单类型：1：开通会员 2：充值金币  3：充值余额  4：手工提现 5：自动提现 6.余额正常还款 7.银行卡正常还款
         * 8.余额逾期还款 9.银行卡逾期还款 10.代还
         */
        params.put("rechargeType", "9"); // 类型 micoolWong
        params.put("principal", FormatUtil.numKbPointFormat(repayDetailBean.getPrincipal())); //本金
        params.put("interest", FormatUtil.numKbPointFormat(repayDetailBean.getInterest())); //利息
        params.put("overdue", FormatUtil.numKbPointFormat(repayDetailBean.getOverdue())); //逾期费用

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.REPAY_BANK, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    payData = response.getObject();
                    if (Build.VERSION.SDK_INT >= 23) {
                        APPayAssistEx.startPay(PayBackActivity.this, payData, serverMode, "com.hongsheng.microfinance.fileProvider");
                    } else {
                        APPayAssistEx.startPay(PayBackActivity.this, payData, serverMode);
                    }
                } else {
                    ToastUtil.getInstant().show(PayBackActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(PayBackActivity.this, msg);// getString(R.string.msg_indentity_code_send_fail));
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(PayBackActivity.this, msg);
            }
        });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 通联支付回调页面处理
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (APPayAssistEx.REQUESTCODE == requestCode) {
            if (null != data) {
                String payRes = null;
                try {
                    JSONObject resultJson = new JSONObject(data.getExtras().getString("result"));
                    payRes = resultJson.getString(APPayAssistEx.KEY_PAY_RES);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != payRes && payRes.equals(APPayAssistEx.RES_SUCCESS)) {
                    Toast.makeText(getApplicationContext(), "支付成功！", Toast.LENGTH_SHORT).show();
                    startActivity(MyBillActivity.class, true);
                } else {
                    Toast.makeText(getApplicationContext(), "支付失败！", Toast.LENGTH_SHORT).show();
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

//        if(requestCode == REQUESTCODE && resultCode == RESULTCODE){                 //从 YBPayActivity 页面易宝支付成功返回处理逻辑结束当前页面
//            PayBackActivity.this.finish();
//        }

    }
}
